package org.ii.infrastructure.flow;

import org.ii.infrastructure.web.UrlUtil;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.StringUtils;
import org.springframework.webflow.context.servlet.DefaultFlowUrlHandler;

/**
 * Custom Flow Url Handler, used to remove portal information from the URL when building the flow ID.
 */
public class CustomFlowUrlHandler extends DefaultFlowUrlHandler {
	@Override
	public String getFlowId(final HttpServletRequest request) {
		final String pathInfo = request.getPathInfo();
		if (pathInfo != null) {
			return pathInfo.substring(1);
		} else {
			final String servletPath = request.getServletPath();
			if (StringUtils.hasText(servletPath)) {
				final int dotIndex = servletPath.lastIndexOf('.');
				if (dotIndex != -1) {
					return UrlUtil.getStrippedUrl(servletPath.substring(1, dotIndex));
				} else {
					return UrlUtil.getStrippedUrl(servletPath.substring(1));
				}
			} else {
				final String contextPath = request.getContextPath();
				if (StringUtils.hasText(contextPath)) {
					return UrlUtil.getStrippedUrl(request.getContextPath()
							.substring(1));
				} else {
					return null;
				}
			}
		}
	}
}
